const express = require("express");
const { getDb, saveDb } = require("./db");

// 1. 创建路由实例
// 路由实例其实就相当于一个mini Express 实例
const router = express.Router();

// 2. 配置路由
router.get("/todos", async (req, res, next) => {
  try {
    const data = await getDb();
    res.status(200).json({
      todos: data.todos,
    });
  } catch (err) {
    // next() 往后匹配下一个中间件
    // next('route') 往后匹配当前中间件堆栈中的下一个
    next(err); // 跳过所有剩余的无错误处理路由和中间件函数
  }
});

router.get("/todos/:id", async (req, res, next) => {
  try {
    const { id } = req.params;
    const data = await getDb();
    const todos = data.todos;
    const todo = todos.find((o) => o.id === +id);
    if (!todo) {
      return res.status(404).end();
    }
    res.status(200).json({
      todo: todo,
    });
  } catch (error) {
    next(err);
  }
});

router.post("/todos", async (req, res, next) => {
  try {
    const db = await getDb();
    const { todo } = req.body;
    if (!todo.title) {
      return res.status(422).json({
        error: "title字段必传",
      });
    }

    let lastTodo = db.todos[db.todos.length - 1];
    todo.id = lastTodo ? lastTodo.id + 1 : 1;
    db.todos.push(todo);
    await saveDb(db);
    res.status(200).json({
      todos: todo,
      message: "新增成功",
    });
  } catch (error) {
    next(err);
  }
});

router.patch("/todos/:id", async (req, res, next) => {
  try {
    const { id } = req.params;
    const todo = req.body;
    const db = await getDb();
    const ret = db.todos.find((todo) => todo.id === +id);
    if (!ret) {
      return res.status(404).json();
    }

    Object.assign(ret, todo);
    await saveDb(db);
    res.status(200).json(ret);
  } catch (error) {
    next(err);
  }
});

router.delete("/todos/:id?", async (req, res, next) => {
  try {
    const { id } = req.params;
    if (!id) {
      return res.status(422).json({
        error: "id必传",
      });
    }

    const db = await getDb();
    const index = db.todos.findIndex((todo) => todo.id === +id);
    if (index === -1) {
      return res.status(404).json({
        message: "暂无数据",
      });
    }

    db.todos.splice(index, 1);
    await saveDb(db);
    res.status(204).json({
      message: "删除成功",
    });
  } catch (error) {
    next(err);
  }
});

// 3. 导出路由实例
module.exports = router;

// 4. 将路由集成到 Express 实例应用中
